<template>
  <el-card style="width: 400px; min-width: 400px; padding: 10px">
    <el-form ref="form" :model="form" :rules="rules">
      <div style="display: flex; justify-content: center; margin-bottom: 20px">
        <img src="@/assets/img/logo.png" width="200" />
      </div>

      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名"></el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="密码"
        ></el-input>
      </el-form-item>

      <el-form-item prop="passwordCheck">
        <el-input
          v-model="form.passwordCheck"
          type="password"
          placeholder="确认密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <div>
          <el-button type="primary" @click="register" style="width: 100%"
            >注册</el-button
          >
          <!-- <el-button type="primary" @click="login">去登录</el-button> -->
        </div>
        <div @click="regedit">
          <span class="change-reg" @click="login">已经有账号？去登录</span>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ElMessage } from "element-plus";
export default {
  emits: ["login"],
  data() {
    const valicateUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      callback();
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      }
      callback();
    };
    const validatePasswordCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("确认密码不能为空不能为空"));
      } else if (value !== this.form.password) {
        return callback(new Error("两次输入密码不一致"));
      }
      callback();
    };
    return {
      form: {
        username: "",
        password: "",
        passwordCheck: "",
      },
      rules: {
        username: [{ validator: valicateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        passwordCheck: [{ validator: validatePasswordCheck, trigger: "blur" }],
      },
    };
  },
  methods: {
    // 还需要正则判断
    register() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
          });
          this.axios.post("/user/register", this.form).then((res) => {
            loading.close();
            if (res.data.code == 200) {
              ElMessage.success({ message: "注册成功，请登录！" });
            }
          });
        }
      });
    },
    login() {
      this.$emit("login");
    },
  },
};
</script>

<style>
.nav {
  display: flex;
  justify-content: space-around;
  padding: 20px;
}
.nav > div {
  font-size: 20px;
  padding: 0.5em;
  cursor: pointer;
}
.selected {
  border-bottom: 3px #409eff solid;
}
</style>